package com.ruoyi.zsyh.controller;

import java.math.BigDecimal;
import java.util.*;

import com.ruoyi.common.utils.GetWxOrderno;
import com.ruoyi.common.utils.RequestHandler;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.zsyh.domain.ZsyhServiceSettle;
import com.ruoyi.zsyh.service.IZsyhServiceSettleService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 抽成结算Controller
 * 
 * @author yuexl
 * @date 2022-03-18
 */
@Controller
@RequestMapping("/zsyh/serviceOrderSettle")
public class ZsyhServiceSettleController extends BaseController
{
    private String prefix = "zsyh/serviceOrderSettle";

    @Value("${wxconfig.appIdAppletUser}")
    private String appIdApplet;

    @Value("${wxconfig.appSecretAppletUser}")
    private String appSecretApplet;

    @Value("${wxconfig.partner}")
    private String partner;

    @Value("${wxconfig.partnerKey}")
    private String partnerKey;

    @Value("${wxconfig.notifyUrlFactoryRecharge}")
    private String notifyUrlFactoryRecharge;

    @Autowired
    private IZsyhServiceSettleService zsyhServiceSettleService;

    @RequiresPermissions("zsyh:serviceOrderSettle:view")
    @GetMapping()
    public String serviceOrderSettle()
    {
        return prefix + "/serviceOrderSettle";
    }

    /**
     * 查询抽成结算列表
     */
    @RequiresPermissions("zsyh:serviceOrderSettle:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZsyhServiceSettle zsyhServiceSettle)
    {
        startPage();
        List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(zsyhServiceSettle);
        return getDataTable(list);
    }

    /**
     * 导出抽成结算列表
     */
    @RequiresPermissions("zsyh:serviceOrderSettle:export")
    @Log(title = "抽成结算", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZsyhServiceSettle zsyhServiceSettle)
    {
        List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(zsyhServiceSettle);
        ExcelUtil<ZsyhServiceSettle> util = new ExcelUtil<ZsyhServiceSettle>(ZsyhServiceSettle.class);
        return util.exportExcel(list, "抽成结算数据");
    }

    /**
     * 新增抽成结算
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存抽成结算
     */
    @RequiresPermissions("zsyh:serviceOrderSettle:add")
    @Log(title = "抽成结算", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ZsyhServiceSettle zsyhServiceSettle)
    {
        return toAjax(zsyhServiceSettleService.insertZsyhServiceSettle(zsyhServiceSettle));
    }

    /**
     * 修改抽成结算
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ZsyhServiceSettle zsyhServiceSettle = zsyhServiceSettleService.selectZsyhServiceSettleById(id);
        mmap.put("zsyhServiceSettle", zsyhServiceSettle);
        return prefix + "/edit";
    }

    /**
     * 修改保存抽成结算
     */
    @RequiresPermissions("zsyh:serviceOrderSettle:edit")
    @Log(title = "抽成结算", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZsyhServiceSettle zsyhServiceSettle)
    {
        return toAjax(zsyhServiceSettleService.updateZsyhServiceSettle(zsyhServiceSettle));
    }

    /**
     * 删除抽成结算
     */
    @RequiresPermissions("zsyh:serviceOrderSettle:remove")
    @Log(title = "抽成结算", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(zsyhServiceSettleService.deleteZsyhServiceSettleByIds(ids));
    }

    /**
     * 服务费结算
     */
    @RequiresPermissions("zsyh:serviceOrderSettle:remove")
    @Log(title = "服务费结算", businessType = BusinessType.DELETE)
    @PostMapping( "/orderSettle")
    @ResponseBody
    public AjaxResult orderSettle(String id) throws Exception {
        ZsyhServiceSettle zsyhServiceSettle = zsyhServiceSettleService.selectZsyhServiceSettleById(id);
        BigDecimal settleMoney;
        Map<String, String> m = new HashMap<>();
        if("1".equals(zsyhServiceSettle.getSettleType())){
            //会长结算
            settleMoney = zsyhServiceSettle.getAgentSettleMoney();
            m.put("openid",zsyhServiceSettle.getAgentOpenid());
        }else{
            //市县结算
            settleMoney = zsyhServiceSettle.getRakerSettleMoney();
            m.put("openid",zsyhServiceSettle.getRakerOpenid());
        }
        m.put("orderId",id);
        m.put("money",settleMoney.toString());
//        m.put("money","0.3");//测试金额
        m.put("spbillCreateIp","127.0.0.1");
        Map<String, Object> responseMap = sendPayBZJ(m);
        if(responseMap != null && responseMap.size() > 0){
            if("SUCCESS".equals(responseMap.get("result_code").toString())){
                String paymentNo = responseMap.get("payment_no").toString();
                System.out.println("调用成功");
                //调用成功，修改申请状态，转账状态
                zsyhServiceSettle.setSettleName(ShiroUtils.getLoginName());
                zsyhServiceSettle.setSettleStatue("2");
                zsyhServiceSettle.setCreateTime(new Date());
                zsyhServiceSettle.setTransactionId(paymentNo);
                zsyhServiceSettleService.updateZsyhServiceSettle(zsyhServiceSettle);
                return AjaxResult.success("操作成功");
            }else{
                String err_code = responseMap.get("err_code").toString();
                String msg = "操作失败";
                switch (err_code){
                    case "AMOUNT_LIMIT":msg += ",金额超限!";break;
                    case "NOTENOUGH":msg += ",您的付款帐号余额不足或资金未到账!";break;
                    case "SYSTEMERROR":msg += ",系统繁忙，请稍后再试!";break;
                    case "V2_ACCOUNT_SIMPLE_BAN":msg += ",用户微信支付账户未知名，无法付款!";break;
                    case "SENDNUM_LIMIT":msg += ",该用户今日付款次数超过限制,如有需要请登录微信支付商户平台更改API安全配置!";break;
                    case "MONEY_LIMIT":msg += ",已经达到今日付款总额上限/已达到付款给此用户额度上限!";break;
                    case "FREQ_LIMIT":msg += ",超过频率限制，请稍后再试!";break;
                    default:break;
                }
                return AjaxResult.error(msg);
            }
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 订单分红转账
     * @param m
     * @return
     * @throws Exception
     */
    public Map<String, Object> sendPayBZJ(Map<String, String> m)throws Exception {

        String openId = m.get("openid");
        // 1 参数
        // 订单号
        String orderId = m.get("orderId");
        // 总金额以分为单位，不带小数点
        String totalFee = StringUtils.getMoney(m.get("money"));

        // 订单生成的机器 IP
        String spbill_create_ip = m.get("spbillCreateIp");

        // ---必须参数
        // 商户号
        String mch_id = partner;
        // 随机字符串
        String nonce_str = StringUtils.getNonceStr();

        String desc = "订单分红转账";

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", appIdApplet);
        packageParams.put("mchid", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("desc", desc);
        packageParams.put("partner_trade_no", orderId);
        // 这里写的金额为1 分到时修改
        packageParams.put("amount", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("check_name", "NO_CHECK");
        packageParams.put("openid", openId);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appIdApplet, appSecretApplet, partnerKey);

        String sign = reqHandler.createSign(packageParams);
        logger.info("第一次签名------------------------------" + sign);
        System.out.println("第一次签名------------------------------" + sign);
        String xml = "<xml>" + "<mch_appid>" + appIdApplet + "</mch_appid>" + "<mchid>"
                + mch_id + "</mchid>" + "<nonce_str>" + nonce_str
                + "</nonce_str>"
                + "<partner_trade_no>" + orderId + "</partner_trade_no>"
                + "<openid>" + openId + "</openid>"
                + "<check_name>NO_CHECK</check_name>"
                + "<amount>" + totalFee + "</amount>"
                + "<desc>"+ desc +"</desc>"
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                + "<sign>" + sign + "</sign>"
                + "</xml>";
        String createOrderURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";


        Map<String, Object> map = new GetWxOrderno().sendPost(createOrderURL, xml);
        logger.info("info---------------------------------------------------------获取到的预支付ID：" + map);
        System.out.println("获取到的预支付ID：" + map);

        return map;
    }

}
